package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressMapper;
import com.sky.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    /**
     * 新增地址信息
     * @param addressBook
     */
    @Override
    public void add(AddressBook addressBook) {

        //判断是否有地址了，没有就把这个地址设置成默认地址
        addressBook.setIsDefault(StatusConstant.ENABLE);
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> addressBookList = addressMapper.getAddressByCondition(addressBook);
        if(!addressBookList.isEmpty()) {
            addressBook.setIsDefault(StatusConstant.DISABLE);
        }

        addressMapper.add(addressBook);
    }

    /**
     * 查询用户所有地址信息
     * @return
     */
    @Override
    public List<AddressBook> getAddressList() {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .build();
        return addressMapper.getAddressByCondition(addressBook);
    }

    /**
     * 根据id查询用户地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getAddressById(Long id) {
        return addressMapper.getAddressById(id);
    }


    /**
     * 查询用户默认地址
     * @return
     */
    @Override
    public AddressBook getDefaultAddress() {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .isDefault(StatusConstant.ENABLE)
                .build();
        List<AddressBook> addressBookList = addressMapper.getAddressByCondition(addressBook);
        if(addressBookList.isEmpty()) {
            addressBook.setIsDefault(null);
            return addressMapper.getAddressByCondition(addressBook).get(0);
        }
        return addressBookList.get(0);
    }

    /**
     * 修改用户地址信息
     * @param addressBook
     * @return
     */
    @Override
    public void update(AddressBook addressBook) {
        addressMapper.upadate(addressBook);
    }

    /**
     * 修改默认地址
     * @param addressBook
     * @return
     */
    @Override
    public void updateDefault(AddressBook addressBook) {

        //将全部地址改成不默认地址
        addressMapper.upadate(AddressBook.builder().userId(BaseContext.getCurrentId()).isDefault(StatusConstant.DISABLE).build());

        //修改地址为默认地址
        addressBook.setIsDefault(StatusConstant.ENABLE);
        addressMapper.upadate(addressBook);
    }

    /**
     * 根据id删除地址
     * @param id
     * @return
     */
    @Override
    public void delete(Long id) {
        addressMapper.delete(id);
    }

}
